﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StoreClientModule;
using StoreClientModuleEx;
using uCoreClasses;

namespace MBBStoreClient
{
    public partial class frmSalesEntry : Form
    {
        SalesEntry se = new SalesEntry();
        DataTable item = new DataTable();
        List<ContentDetailType> cdetail = new List<ContentDetailType>();
        StockManager sm = new StockManager();

        public frmSalesEntry()
        {
            InitializeComponent();

            btnClose.Click += new EventHandler(btnClose_Click);
            panel2.EnabledChanged += new EventHandler(panel2_EnabledChanged);

            se.ProcessCompleted += new ModuleEventHandler(se_ProcessCompleted);
            se.ProcessError += new ModuleEventHandler(se_ProcessError);
            btnAdd.LostFocus += new EventHandler(btnAdd_LostFocus);
            
            txtSoldTo.KeyPress += new KeyPressEventHandler(txtSoldTo_KeyPress);
            txtSalesman.KeyPress += new KeyPressEventHandler(txtSalesman_KeyPress);
            txtDescription.KeyPress += new KeyPressEventHandler(txtDescription_KeyPress);

            txtQty.LostFocus += new EventHandler(txtQty_LostFocus);
            txtUnitPrice.LostFocus += new EventHandler(txtUnitPrice_LostFocus);
            btnAdd.Click += new EventHandler(btnAdd_Click);
            btnCommit.Click += new EventHandler(btnCommit_Click);
            mnuCancel.Click += new EventHandler(mnuCancel_Click);

            txtSoldTo.LostFocus += new EventHandler(txtSoldTo_LostFocus);
            sm.PreloadUnits();
            sm.ProcessCompleted += new UnityCore.CoreHandler(sm_ProcessCompleted);
            sm.ProcessError += new UnityCore.CoreHandler(sm_ProcessError);
        }

        void sm_ProcessError(string pcode, string msg)
        {
            uThreader t = new uThreader();
            t.SafeCall(this, delegate
            {
                MessageBox.Show(msg, pcode, MessageBoxButtons.OK, MessageBoxIcon.Error);
            });
        }
        void sm_ProcessCompleted(string pcode, string msg)
        {
            uThreader t = new uThreader();
            t.SafeCall(this, delegate
            {
                switch (pcode)
                {
                    case "UpdateStock":
                        ControlState(true);
                        foreach (Control ctl in grpSalesDetail.Controls)
                        {
                            if (!(ctl is DateTimePicker) && !(ctl is Label))
                            {
                                ctl.Text = "";
                            }
                        }
                        foreach (Control ctl in pnlAdd.Controls)
                        {
                            if (!(ctl is Button) && !(ctl is Label))
                            {
                                ctl.Text = "";
                            }
                        }
                        cdetail.Clear();
                        txtInvoiceType.Text = "Sales";
                        txtTotal.Text = "";
                        item.Rows.Clear();
                        pnlMsg.Visible = false;
                        MessageBox.Show("Sales record was successfully saved.", "Sales Entry", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        break;
                }
            });
        }

        void txtSoldTo_LostFocus(object sender, EventArgs e)
        {
            if (txtSoldTo.Text != "")
                se.GetSoldToInfo(txtSoldTo.Text);
        }

        void mnuCancel_Click(object sender, EventArgs e)
        {
            if (grdItems.SelectedRows.Count == 1)
            {
                DialogResult dlg = MessageBox.Show("Are you sure?", "Entry Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dlg == DialogResult.Yes)
                {
                    cdetail.RemoveAt(grdItems.SelectedRows[0].Index);
                    item.Rows[grdItems.SelectedRows[0].Index].Delete();
                }
            }
        }

        void btnCommit_Click(object sender, EventArgs e)
        {
            try
            {
                bool hasError = false;
                if (txtSoldTo.Text == "") hasError = true;
                if (txtInvoice.Text == "") hasError = true;
                if (txtInvoiceType.Text == "") hasError = true;
                if (txtSalesman.Text == "") hasError = true;
                if (item.Rows.Count == 0) hasError = true;
                if (hasError)
                {
                    MessageBox.Show("Invalid inputs detected! Please check item list and sale details.",
                        "Commit Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                SalesType st = new SalesType();
                st.fStoreID = Common.lStoreID.ToUpper();
                st.fSoldTo = txtSoldTo.Text;
                st.fAddress = txtAddress.Text;
                st.fTelNo = txtTelNo.Text;
                st.fSalesman = txtSalesman.Text;
                st.fRef = txtRef.Text;
                st.fORNum = txtOR.Text;
                st.fInvoice = txtInvoice.Text;
                st.fInvoiceType = txtInvoiceType.Text;
                st.fDate = txtDate.Value.ToShortDateString();
                st.Items = new SalesItemType[item.Rows.Count];
                for (int i = 0; i < st.Items.Length; i++)
                {
                    st.Items[i].fInvoice = txtInvoice.Text;
                    st.Items[i].fBarcode = item.Rows[i]["Barcode"].ToString();
                    st.Items[i].fQty = item.Rows[i]["Qty"].ToString();
                    st.Items[i].fUnit = item.Rows[i]["Unit"].ToString();
                    st.Items[i].fDescription = item.Rows[i]["Description"].ToString();
                    st.Items[i].fUnitPrice = item.Rows[i]["UnitPrice"].ToString();
                    st.Items[i].fContentQty = cdetail[i].fQty;
                    st.Items[i].fContentUnit = cdetail[i].fUnit;
                    st.Items[i].fContentBarcode = cdetail[i].fBarcode;
                }
                sm.ItemsToUpdate = st.Items;
                pnlMsg.Visible = true;
                ControlState(false);
                se.Add(st);
                //se.AddMix(st);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error during commit! Please check your input.", "Commit Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void btnAdd_Click(object sender, EventArgs e)
        {
            AddItem();
        }
        void AddItem()
        {
            bool inpValid = true;
            //Add if new item
            string[] invChar = { "'", "#", "%", "@", "\"" };
            foreach (Control ctl in pnlAdd.Controls)
            {
                if (ctl is TextBox || ctl is ComboBox)
                {
                    for (int i = 0; i < invChar.Length; i++)
                    {
                        if (ctl.Text.Contains(invChar[i])) inpValid = false;
                        if (ctl.Text == "") inpValid = false;
                    }
                }
            }
            if (inpValid)
            {
                ContentDetailType cdt = se.GetContent(txtDescription.Text, txtUnit.Text);
                if (cdt.fBarcode != "N\\A")
                {
                    cdetail.Add(cdt);

                    if (float.Parse(txtQty.Text) > 0 && txtUnit.Text != "")
                    {
                        //check if decimal
                        float dec = (float)(Math.Round(decimal.Parse(txtQty.Text), 0)) - float.Parse(txtQty.Text);
                        if (txtUnit.Text == "PCS" && dec != 0)
                        {
                            MessageBox.Show("Invalid quantity detected! The unit is in PCS, the quantity should not contain decimal values.", "Add Item", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        DataRow dr = item.NewRow();
                        dr["Barcode"] = cdt.fBarcode;
                        dr["Qty"] = txtQty.Text;
                        dr["Unit"] = txtUnit.Text;
                        dr["Description"] = txtDescription.Text;
                        dr["Amount"] = Common.FormatCurrency(txtUnitPrice.Text);
                        float amt = float.Parse(txtUnitPrice.Text) / float.Parse(txtQty.Text);
                        dr["UnitPrice"] = Common.FormatCurrency(amt);
                        
                        
                        item.Rows.Add(dr);
                        txtTotal.Text = Common.FormatCurrency(ComputeTotal().ToString());
                        ResetAdd();
                    }
                    else
                    {
                        MessageBox.Show("Invalid values have been detected!\n" +
                            " You could have a missing field or inappropriate values.", "Add Item", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                else
                {

                    MessageBox.Show("Invalid values have been detected!\n" +
                           "The system could not identify the product or an inaapropriate unit is assigned to the item.", "Add Item", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
            }
            else
            {
                MessageBox.Show("Invalid inputs! The characters ', #, %, @, \" are not valid.", "Item Add", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        void txtUnitPrice_LostFocus(object sender, EventArgs e)
        {
            txtUnitPrice.Text = Common.FormatCurrency(txtUnitPrice.Text);
        }
        void txtQty_LostFocus(object sender, EventArgs e)
        {
            txtQty.Text = Common.FormatNumber(txtQty.Text);
        }

        void txtDescription_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar != (char)27 && e.KeyChar != (char)13)
                {
                    if (txtDescription.Items.Count > 0) txtDescription.DroppedDown = true; else txtDescription.DroppedDown = false;
                    se.AutoDescription(txtDescription.Text);
                }
                else
                {
                    txtDescription.DroppedDown = false;
                }
            }
            catch (Exception ex)
            {
            }
        }
        void txtSalesman_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar != (char)27 && e.KeyChar != (char)13)
                {
                    if (txtSalesman.Items.Count > 0) txtSalesman.DroppedDown = true; else txtSalesman.DroppedDown = false;
                    se.AutoSalesman(txtSalesman.Text);
                }
                else
                {
                    txtSalesman.DroppedDown = false;
                }
            }
            catch (Exception ex)
            {
            }
        }
        void txtSoldTo_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar != (char)27 && e.KeyChar != (char)13)
                {
                    if (txtSoldTo.Items.Count > 0) txtSoldTo.DroppedDown = true; else txtSoldTo.DroppedDown = false;
                    se.AutoSoldTo(txtSoldTo.Text);
                }
                else
                {
                    txtSoldTo.DroppedDown = false;
                }
            }
            catch (Exception ex)
            {
            }
        }
        
        void btnAdd_LostFocus(object sender, EventArgs e)
        {
            txtQty.Focus();
        }
        void ControlState(bool s)
        {
            grpSalesDetail.Enabled = s;
            pnlAdd.Enabled = s;
            btnCommit.Enabled = s;
        }
        void ResetAdd()
        {
            txtQty.Text = "";
            txtUnit.Text = "";
            txtDescription.Text = "";
            txtUnitPrice.Text = "";
            txtQty.Focus();
        }
        float ComputeTotal()
        {
            float res = 0f;
            if (item.Rows.Count > 0)
            {
                for (int i = 0; i < item.Rows.Count; i++)
                {
                    res += float.Parse(item.Rows[i]["Amount"].ToString());
                }
            }
            return res;
        }



        void se_ProcessError(string procCode, string msg)
        {
            uThreader t = new uThreader();
            t.SafeCall(this, delegate
            {
                MessageBox.Show(msg, procCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
                ControlState(true);
                pnlMsg.Visible = false;
            });
        }
        void se_ProcessCompleted(string procCode, string msg)
        {
            uThreader t = new uThreader();
            t.SafeCall(this, delegate
            {

                try
                {
                    if (procCode == "AutoDescription")
                    {
                        if (se.ListAutoDescription.Length > 0)
                        {
                            txtDescription.Items.Clear();
                            txtDescription.Items.AddRange(se.ListAutoDescription);
                            txtDescription.SelectionStart = txtDescription.Text.Length;
                        }
                    }
                    if (procCode == "AutoUnit")
                    {
                        if (se.ListAutoUnit.Length > 0)
                        {
                            txtUnit.Items.Clear();
                            txtUnit.Items.AddRange(se.ListAutoUnit);
                            txtUnit.SelectionStart = txtUnit.Text.Length;
                        }
                    }
                    if (procCode == "AutoSoldTo")
                    {
                        if (se.ListAutoSoldTo.Length > 0)
                        {
                            txtSoldTo.Items.Clear();
                            txtSoldTo.Items.AddRange(se.ListAutoSoldTo);
                            txtSoldTo.SelectionStart = txtSoldTo.Text.Length;
                        }
                    }
                    if (procCode == "AutoSalesman")
                    {
                        if (se.ListAutoSalesman.Length > 0)
                        {
                            txtSalesman.Items.Clear();
                            txtSalesman.Items.AddRange(se.ListAutoSalesman);
                            txtSalesman.SelectionStart = txtSalesman.Text.Length;
                        }
                    }

                    if (procCode == "Add")
                    {
                        //sm.UpdateStock(sm.ItemsToUpdate);
                        ControlState(true);
                        foreach (Control ctl in grpSalesDetail.Controls)
                        {
                            if (!(ctl is DateTimePicker) && !(ctl is Label))
                            {
                                ctl.Text = "";
                            }
                        }
                        foreach (Control ctl in pnlAdd.Controls)
                        {
                            if (!(ctl is Button) && !(ctl is Label))
                            {
                                ctl.Text = "";
                            }
                        }
                        cdetail.Clear();
                        txtTotal.Text = "";
                        txtInvoiceType.Text = "Sales";
                        item.Rows.Clear();
                        pnlMsg.Visible = false;
                        MessageBox.Show("Sales record was successfully saved.", "Sales Entry", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                    if (procCode == "GetSoldToInfo")
                    {
                        txtTelNo.Text = se.soldInfo.telNo;
                        txtAddress.Text = se.soldInfo.address;
                        txtRef.Text = se.soldInfo.refNum;
                    }
                }
                catch (Exception ex)
                {
                }
            
            });
        }


        void panel2_EnabledChanged(object sender, EventArgs e)
        {
            if (!panel2.Enabled)
            {
                panel2.BackColor = Color.MidnightBlue;
            }
            else
            {
                panel2.BackColor = Color.RoyalBlue;
                this.Select();
                txtQty.Focus();
            }
        }
        void btnClose_Click(object sender, EventArgs e)
        {
            pnlForm.Dispose();
            this.Dispose();
        }
        public Panel PanelForm
        {
            get { return pnlForm; }
        }
        public void Initialize(string Title)
        {
            this.Select();
            lblText.Text = Title;
            se.AutoDescription("");
            se.AutoSoldTo("");
            se.AutoSalesman("");
            se.AutoUnit("");
            //se.AutoInvoiceType();

            item.Columns.Add("Qty");
            item.Columns.Add("Unit");
            item.Columns.Add("Description");
            item.Columns.Add("UnitPrice");
            item.Columns.Add("Amount");
            item.Columns.Add("Barcode");

            grdItems.Font = new Font("Courier New", 8f, FontStyle.Regular);
            grdItems.DataSource = item;
            grdItems.Columns[0].Width = (grdItems.Width * 9) / 100;
            grdItems.Columns[1].Width = (grdItems.Width * 10) / 100;
            grdItems.Columns[2].Width = (grdItems.Width * 40) / 100;
            grdItems.Columns[3].Width = (grdItems.Width * 19) / 100;
            grdItems.Columns[4].Width = (grdItems.Width * 19) / 100;
            
            grdItems.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

        }
    }
}
